package view;

import java.io.IOException;
import java.io.PrintStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.LoginException;

import controller.Cashier;

/**
 * Servlet implementation class Controller
 */
public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private Cashier cashier = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Controller() {
        super();
        cashier = Cashier.getInstance();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		super.doGet(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//PrintStream tela = new PrintStream(response.getOutputStream());
		//tela.println("<HTML><BODY bgcolor=\"yellow\">"); 
		
		String forward = "/Index.jsp";
		String loginStatus = "";
		try {
			cashier.doLogin(request.getParameter("login"), request.getParameter("password"));
		
			forward = "/Controller.jsp";
			//tela.println("<div align=\"center\">Obrigado, o digitado foi : " + request.getParameter("login") + "</div>");  
			//tela.println("<BR><P>");  
			//tela.println("<div align=\"center\">Saldo: " + 10 + "</div>");
			//tela.println("</BODY></HTML>"); 
			
			//tela.close();
		
			loginStatus = "Bem vindo ao seu Livro Caixa";
		
		} catch (LoginException e) {
			
			loginStatus = "Login ou senha inválidos";
			//tela.println("<div align=\"center\">Obrigado, mas seu login ou senha est�o inv�lidos...</div>");  
			//tela.println("<BR><P>");
			//tela.println("</BODY></HTML>"); 
			
			//tela.close();
		}
		
		  
		request.setAttribute("loginStatus", loginStatus);
		request.getSession().setAttribute("login", request.getParameter("login"));
		request.getSession().setAttribute("password", request.getParameter("password"));
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(forward);
		if (dispatcher != null) {
			dispatcher.forward(request, response);
		}
		
	}

}
